package net.ojbk.study.twobox.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.ojbk.study.twobox.beans.constraint.Constraint;
import net.ojbk.study.twobox.beans.form.post.SupperPostForm;
import net.ojbk.study.twobox.beans.form.query.SupperQueryForm;
import net.ojbk.study.twobox.beans.po.Department;
import net.ojbk.study.twobox.dao.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import tk.mybatis.mapper.common.Mapper;

import java.lang.reflect.Field;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2019/4/11
 * Time: 18:21
 * Description: No Description
 */
public abstract class SupperService<T> {
    protected int pageSize = 15;

    @Autowired
    protected Mapper<T> dao;

    @Autowired
    protected SupperQueryForm<T> queryForm;

    @Autowired
    protected SupperPostForm<T> postForm;

    // 属性验证异常处理
    public void validated(BindingResult br, Class aClass) throws Exception {
        List<ObjectError> errors = br.getAllErrors();
        if (errors.size() > 0) {
            Field[] fields = aClass.getDeclaredFields();
            for (Field field : fields) {
                FieldError fieldError = br.getFieldError(field.getName());
                if (fieldError != null)
                    throw new Exception(fieldError.getDefaultMessage());
            }
        }
    }

    // 增加删改查
    /**
     * 增
     */
    public abstract void addOne(T o, BindingResult br) throws Exception;

    /**
     * 删
     */
    public abstract void deleteOne(int id) throws Exception;

    /**
     * 改
     */
    public abstract void updateOne(T o, BindingResult br) throws Exception;

    public PageInfo<T> getAll(Integer currentPage) throws Exception {
        // 只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
        // 我觉得应该是内存分页。其实插件对mybatis执行流程进行了增强，添加了limit以及count查询，属于物理分页
        PageHelper.startPage(currentPage, pageSize);
        List<T> dataList = dao.selectAll();
        PageInfo<T> page = new PageInfo<>(dataList);
        return page;
    }

    /**
     * 条件查
     */
    public PageInfo<T> getAllByConstraint(Constraint<T> constraint) throws Exception {
        PageHelper.startPage(constraint.getCurrentPage(), pageSize);
        List<T> dataList = dao.select(constraint.getConstraint());
        PageInfo<T> page = new PageInfo<>(dataList);
        return page;
    }

    // 获得页面元素
    public SupperPostForm<T> getPostForm() throws Exception {
        return postForm;
    }

    public SupperQueryForm<T> getQueryForm() throws Exception {
        return queryForm;
    }
}
